//
//  XPMessageQueueCellView.m
//  QQ
//
//  Created by nhope on 2017/4/26.
//  Copyright © 2017年 xiaopin. All rights reserved.
//

#import "XPMessageQueueCellView.h"
#import "XPMessageContactModel.h"

@interface XPMessageQueueCellView ()

@property (weak) IBOutlet NSButton *closeButton;
@property (weak) IBOutlet NSImageView *avatarImageView;
@property (weak) IBOutlet NSTextField *nameLabel;
@property (weak) IBOutlet NSTextField *messageLabel;
@property (nonatomic, strong) NSTrackingArea *trackingArea;

@end

@implementation XPMessageQueueCellView

#pragma mark - Lifecycle

- (void)awakeFromNib {
    [super awakeFromNib];
    self.wantsLayer = YES;
    self.avatarImageView.wantsLayer = YES;
    self.avatarImageView.layer.cornerRadius = 20.0;
    self.avatarImageView.layer.masksToBounds = YES;
    [self readdTrackingArea];
}

- (void)prepareForReuse {
    [super prepareForReuse];
    self.layer.backgroundColor = [[NSColor clearColor] CGColor];
    if (nil != _trackingArea) {
        [self removeTrackingArea:_trackingArea];
        _trackingArea = nil;
    }
}

- (void)updateTrackingAreas {
    [super updateTrackingAreas];
    [self readdTrackingArea];
}

#pragma mark - Action

- (void)mouseEntered:(NSEvent *)event {
    [super mouseEntered:event];
    [self.closeButton setHidden:NO];
}

- (void)mouseExited:(NSEvent *)event {
    [super mouseExited:event];
    [self.closeButton setHidden:YES];
}

- (IBAction)closeButtonAction:(NSButton *)sender {
    if (nil != self.didClickedCloseButtonBlock) {
        self.didClickedCloseButtonBlock(self);
    }
}


#pragma mark - Public

- (void)showWithContact:(XPMessageContactModel *)contact {
    NSColor *color = contact.selected ? rgbColor(239.0, 241.0, 245.0) : [NSColor clearColor];
    self.layer.backgroundColor = color.CGColor;
    self.avatarImageView.image = [NSImage imageNamed:contact.avatar];
    self.nameLabel.stringValue = contact.username;
    self.messageLabel.stringValue = contact.message;
}

#pragma mark - Private

- (void)readdTrackingArea {
    if (nil != _trackingArea) {
        [self removeTrackingArea:_trackingArea];
        _trackingArea = nil;
    }
    _trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways owner:self userInfo:nil];
    [self addTrackingArea:_trackingArea];
}

@end
